/* eslint-disable */
import { JSEncrypt } from 'jsencrypt'; //密码加密解密工具
import settings from '@/settings.js';
import { useUserStore } from '@/store/modules/user.js';
import { ref } from 'vue';
import msg from '@/utils/layer';
import router from '../router';

export default {
	//加密密码
	encryptedData(data) {
		// 新建JSEncrypt对象
		let encryptor = new JSEncrypt();
		// 设置公钥
		encryptor.setPublicKey(settings.pubRsaKey);
		// 加密数据
		return encryptor.encrypt(data);
	},

	//localStorage获取缓存
	getItem(key) {
		try {
			return JSON.parse(window.localStorage.getItem(key));
		} catch (err) {
			return null;
		}
	},

	//储存信息
	setItem(key, val) {
		window.localStorage.setItem(key, JSON.stringify(val));
	},

	//清除所有缓存
	clear() {
		window.localStorage.clear();
	},

	//获取对应缓存key
	keys(index) {
		return window.localStorage.key(index);
	},

	//清除对应缓存
	removeItem(key) {
		window.localStorage.removeItem(key);
	},

	//格式化时间（苹果时间只支持 / 写法）
	formattingTime(val) {
		return val.replace(/-/g, '/');
	},

	//精确乘法
	accMul(arg1, arg2) {
		var m = 0,
			s1 = arg1.toString(),
			s2 = arg2.toString();
		try {
			m += s1.split('.')[1].length;
		} catch (e) {}

		try {
			m += s2.split('.')[1].length;
		} catch (e) {}

		return (Number(s1.replace('.', '')) * Number(s2.replace('.', ''))) / Math.pow(10, m);
	},

	//精确除法
	accDiv(arg1, arg2) {
		var t1 = 0,
			t2 = 0,
			r1,
			r2;
		try {
			t1 = arg1.toString().split('.')[1].length;
		} catch (e) {}

		try {
			t2 = arg2.toString().split('.')[1].length;
		} catch (e) {}

		r1 = Number(arg1.toString().replace('.', ''));
		r2 = Number(arg2.toString().replace('.', ''));
		return (r1 / r2) * Math.pow(10, t2 - t1);
	},

	//精确加法
	accAdd(arg1, arg2) {
		var r1, r2, m, c;
		try {
			r1 = arg1.toString().split('.')[1].length;
		} catch (e) {
			r1 = 0;
		}
		try {
			r2 = arg2.toString().split('.')[1].length;
		} catch (e) {
			r2 = 0;
		}
		c = Math.abs(r1 - r2);
		m = Math.pow(10, Math.max(r1, r2));
		if (c > 0) {
			var cm = Math.pow(10, c);
			if (r1 > r2) {
				arg1 = Number(arg1.toString().replace('.', ''));
				arg2 = Number(arg2.toString().replace('.', '')) * cm;
			} else {
				arg1 = Number(arg1.toString().replace('.', '')) * cm;
				arg2 = Number(arg2.toString().replace('.', ''));
			}
		} else {
			arg1 = Number(arg1.toString().replace('.', ''));
			arg2 = Number(arg2.toString().replace('.', ''));
		}
		return (arg1 + arg2) / m;
	},

	// 精确减法
	accSub(arg1, arg2) {
		var r1, r2, m, n;
		try {
			r1 = arg1.toString().split('.')[1].length;
		} catch (e) {
			r1 = 0;
		}
		try {
			r2 = arg2.toString().split('.')[1].length;
		} catch (e) {
			r2 = 0;
		}
		m = Math.pow(10, Math.max(r1, r2)); //last modify by deeka //动态控制精度长度
		n = r1 >= r2 ? r1 : r2;
		return ((arg1 * m - arg2 * m) / m).toFixed(n);
	},

	//获取数字有多少位数
	getNumDigit(value) {
		let num = value || 0;
		let count = 0;
		let TotalNum = 10;
		while (num >= 1) {
			num = num / 10;
			count++;
		}
		for (let i = 1; i < count; i++) {
			TotalNum = TotalNum * 10;
		}
		return TotalNum;
	},

	//截取位数
	TimeDigit(value, n, m) {
		return value.substring(n, m);
	},

	//取N位小数
	Decimal(value, n) {
		var m = Math.pow(10, n);
		if (value.toString().indexOf('-') != -1) {
			return Math.ceil(value * m) / m;
		} else {
			return Math.floor(value * m) / m;
		}
	},

	//对象数组按某个属性分组(例:权限类型分组)
	groupByType(arr, param) {
		var map = {},
			dest = [];
		for (var i = 0; i < arr.length; i++) {
			var ai = arr[i];
			if (ai[param] && !map[ai[param]]) {
				dest.push({
					name: ai[param],
					data: [ai],
				});
				map[ai[param]] = ai;
			} else {
				for (var j = 0; j < dest.length; j++) {
					var dj = dest[j];
					if (dj.name == ai[param]) {
						dj.data.push(ai);
						break;
					}
				}
			}
		}
		return dest;
	},

	//深复制
	extend(o1) {
		var obj1 = {};
		if (o1 instanceof Array) {
			//判断对象是否是数组
			obj1 = [];
		}
		for (var key in o1) {
			var value = o1[key]; // 拓本中的值
			// value内还有引用型数据&& value不为 null 则 需要对value这个对象 再进来 深拷贝一份 返回出来深拷贝后的值
			// obj1[key] = extend(value)
			if (typeof value === 'object' && value !== null) {
				obj1[key] = extend(value);
			} else {
				obj1[key] = value;
			}
		}
		return obj1;
	},

	// 拆分数据
	splitData(data) {
		let url = '';
		for (let k in data) {
			if (data.hasOwnProperty(k)) {
				let value = data[k] || '';
				if (value) {
					url = url + '&' + k + '=' + encodeURIComponent(value);
				}
			}
		}
		return url ? url.substring(1) : '';
	},

	// 拼接参数
	contractUrl(url, data) {
		return url + (url.indexOf('?') < 0 ? '?' : '&') + this.splitData(data);
	},

	//获取当前时间
	getNowTime(type = 'String') {
		const date = new Date();
		const formatObj = {
			y: date.getFullYear(),
			m: date.getMonth() + 1,
			d: date.getDate(),
			h: date.getHours(),
			i: date.getMinutes(),
			s: date.getSeconds(),
			a: date.getDay(),
		};

		function timer(value) {
			return value < 10 ? '0' + value : value;
		}
		if (type == 'String') {
			return formatObj.y + '-' + timer(formatObj.m) + '-' + timer(formatObj.d) + ' ' + timer(formatObj.h) + ':' + timer(formatObj.i) + ':' + timer(formatObj.s);
		} else {
			return formatObj
		}
	},

	//获取N个月之前的日期
	getNMonthsAgoDate(N, date = new Date()) {
		const currentDate = date;
		let year = currentDate.getFullYear();
		let month = currentDate.getMonth() + 2 - N;
		let day = currentDate.getDate();

		// 处理月份的跨年情况
		if (month < 0) {
			year--;
			month += 12;
		}

		let newDate = `${year}-${month}`;
		return newDate;
	},

	//格式化时间 fmt = 'yyyy-MM-dd hh:mm' 返回对应格式时间type=date时间、type=getTime时间戳
	timer(value, fmt = 'yyyy-MM-dd hh:mm', type = 'date') {
		if (!value) return;
		let newTime = new Date();

		try {
			let timeVal = type == 'date' && typeof value == 'string' ? value.replace(/-/g, '/') : value;
			newTime = new Date(timeVal);
		} catch (e) {
			//   newTime = new Date(value);
			//TODO handle the exception
		}
		if (/(y+)/.test(fmt)) {
			fmt = fmt.replace(RegExp.$1, (newTime.getFullYear() + '').substr(4 - RegExp.$1.length));
		}
		let o = {
			'M+': newTime.getMonth() + 1,
			'd+': newTime.getDate(),
			'h+': newTime.getHours(),
			'm+': newTime.getMinutes(),
			's+': newTime.getSeconds(),
		};

		function padLeftZero(str) {
			return ('00' + str).substr(str.length);
		}

		// 遍历这个对象
		for (let k in o) {
			if (new RegExp(`(${k})`).test(fmt)) {
				// console.log(`${k}`)
				let str = o[k] + '';
				fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : padLeftZero(str));
			}
		}
		return fmt;
	},

	//获取饼图数据过长时滚动结束的位置
	getEndValue(data, num = 12) {
		let endValue = 100; //这里一定要注意不显示滚动条的时候一定要把滚动条结束位置设置一下，不然会有bug
		if (data.length > num) {
			//this.xData是横轴的数据，通过后台动态获取的
			endValue = (num / data.length) * 100;
		}
		return endValue;
	},

	//判断当前Token时间是否过期,true是已过期，false是还没过期
	isExpireTime() {
		const userStore = useUserStore();
		let timestamp = userStore.exp; //过期时间
		if (!timestamp) return true; //没有获取到过期时间，那直接返回true

		let time = `${timestamp}`.length == 13 ? timestamp : Number(timestamp) * 1000; //时间戳为10位需*1000，时间戳为13位的话不需乘1000
		var now = new Date();
		if (now > new Date(time)) {
			//当前时间大于过期时间
			return true;
		} else {
			return false;
		}
	},

	//登录过期，退出登录
	loginOut() {
		const store = useUserStore(); //pinia这里才会加在完成
		//只执行一次
		layer.closeAll(); //关闭所有的Message弹窗--在路由拦截器那里也有个通过时间判断是否登录过期的提示，有时会两个提示一起出现
		msg.warning('登录超时，请重新登录！');
		setTimeout(() => {
			store.logout().then((res) => {
				router.push(`/login?redirect=timeOut`);
				location.reload();
			});
		}, 2000);
	},

	// 树形扁平化数据转换
	setTreeData(source) {
		const cloneData = JSON.parse(JSON.stringify(source)); // 对源数据深度克隆
		return cloneData.filter((father) => {
			// 循环所有项，并添加children属性
			father.spread = true
			const branchArr = cloneData.filter((child) => father.id == child.pId); // 返回每一项的子级数组
			branchArr.length > 0 ? (father.children = branchArr) : ''; // 给父级添加一个children属性，并赋值
			return father.pId == 0; // 返回第一层
		});
	},

	//获取某年、某月有多少天
	getDaysInMonth(year, month) {
		return new Date(year, month, 0).getDate();
	},

	//不足位数时补前面补0
	PrefixInteger(num, length) {
		return (Array(length).join('0') + num).slice(-length);
	},

	//转换JSON字符串
	JSONP(value, type = 'array') {
		let data = type == 'array' ? [] : {};
		try {
			data = JSON.parse(value);
		} catch (e) {
			console.log(e);
		}
		return data;
	},

	//合并对象-把第二个对象页面的值赋值给第一个对象
	objAssignment(obj1, obj2) {
		try {
			let objL = JSON.parse(JSON.stringify(obj1))
			let objR = JSON.parse(JSON.stringify(obj2))
			let obj = {}
			Object.keys(objL).forEach(key => {
				obj[key] = !objR[key] ? objL[key] : objR[key]
			})
			return obj
		} catch {
			return obj1
		}
	},
	//对树状数据进行筛选
	multiFilterTree(tree, searchVal, treeKey = 'name') {
		const filteredNodes = [];
		const treeData = JSON.parse(JSON.stringify(tree))
		try {
			for (const node of treeData) {
				const isNameMatch = searchVal === null || (typeof searchVal === 'string' && node[treeKey]?.includes(searchVal));
				if (isNameMatch) {
					const children = node.children ? this.multiFilterTree(node.children, searchVal, treeKey) : [];
					filteredNodes.push({ ...node, children: children.length > 0 ? children : node.children });
				} else {
					const children = node.children ? this.multiFilterTree(node.children, searchVal, treeKey) : [];
					if (children.length > 0) {
						filteredNodes.push({ ...node, children });
					}
				}
			}
		} catch (err) {
			console.log(err)
		}
		return filteredNodes;
	},

	//获取图片的外框轮廓canvas路径
	canvasDrawPath() {
		// const canvas = document.getElementById('conveyorCanvas');
		// const ctx = canvas.getContext('2d');
		
		// const img = new Image();
		// img.src = './src/assets/images/111111.png?' + new Date().getTime();
		// img.onload = function() {
		// 	ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
		// 	const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
		// 	const edges = detectEdges(imageData);
		// 	drawPath(edges);
		// };
		
		// function drawPath(edges) {
		// 	ctx.beginPath();
		// 	ctx.moveTo(edges[0].x, edges[0].y);
		
		// 	for (let i = 1; i < edges.length; i++) {
		// 		ctx.lineTo(edges[i].x, edges[i].y);
		// 	}
		
		// 	ctx.strokeStyle = 'red';
		// 	ctx.stroke();
		// }
		
		
		// function detectEdges(imageData) {
		// 	const width = imageData.width;
		// 	const height = imageData.height;
		// 	const data = imageData.data;
		// 	const edges = [];
		
		// 	// 简单的边缘检测算法
		// 	for (let y = 1; y < height - 1; y++) {
		// 		for (let x = 1; x < width - 1; x++) {
		// 			const index = (y * width + x) * 4;
		// 			const brightness = (data[index] + data[index + 1] + data[index + 2]) / 3;
		
		// 			const rightIndex = (y * width + (x + 1)) * 4;
		// 			const rightBrightness = (data[rightIndex] + data[rightIndex + 1] + data[rightIndex + 2]) / 3;
		
		// 			const bottomIndex = ((y + 1) * width + x) * 4;
		// 			const bottomBrightness = (data[bottomIndex] + data[bottomIndex + 1] + data[bottomIndex + 2]) / 3;
		
		// 			if (Math.abs(brightness - rightBrightness) > 50 || Math.abs(brightness - bottomBrightness) > 50) {
		// 				edges.push({ x, y });
		// 			}
		// 		}
		// 	}
		
		// 	return edges;
		// }
	},
};